package com.group.sliding.controller;

import com.group.sliding.annotation.CacheAddByUserId;
import com.group.sliding.annotation.CacheRemoveByUserId;
import com.group.sliding.constant.Constants;
import com.group.sliding.domain.dto.PayOrderFormDTO;
import com.group.sliding.domain.po.PayOrder;
import com.group.sliding.domain.vo.PayOrderVO;
import com.group.sliding.result.Result;
import com.group.sliding.service.IPayOrderService;
import com.group.sliding.utils.BeanUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@Api(tags = "支付相关接口")
@RestController
@RequestMapping("pay-orders")
@RequiredArgsConstructor
public class PayController {

    private final IPayOrderService payOrderService;

    @ApiOperation("获取支付订单信息")
    @GetMapping("/list")
    @CacheAddByUserId(key = Constants.REDIS_KEY_PAY_ORDERS)
    public Result<List<PayOrderVO>> queryMyPayOrders() {
        log.info("查询支付订单信息列表");
        List<PayOrderVO> payOrderVOS = payOrderService.queryMyPayOrders();
        log.info("查询支付订单信息列表成功 {}", payOrderVOS);
        return Result.success(payOrderVOS);
    }

    @ApiOperation("生成支付单")
    @PostMapping("/create")
    @CacheRemoveByUserId(keys = Constants.REDIS_KEY_PAY_ORDERS)
    public Result<PayOrderVO> createPayOrder(Long orderId) {
        log.info("生成支付单 orderId: {}", orderId);
        PayOrder payOrder = payOrderService.createPayOrder(orderId);
        PayOrderVO payOrderVO = BeanUtils.copyBean(payOrder, PayOrderVO.class);
        log.info("生成支付单成功 {}", payOrderVO);
        return Result.success(payOrderVO);
    }

    @ApiOperation("尝试基于用户余额支付")
    @PostMapping("/pay")
    // 支付订单状态和订单状态可能修改
    // 余额信息也可能变化，需要删除缓存
    @CacheRemoveByUserId(keys = {Constants.REDIS_KEY_PAY_ORDERS, Constants.REDIS_KEY_ORDERS, Constants.REDIS_KEY_USERS})
    public Result<String> tryPayOrderByBalance(PayOrderFormDTO payOrderFormDTO) {
        log.info("尝试基于用户余额支付 {}", payOrderFormDTO);
        payOrderService.tryPayOrderByBalance(payOrderFormDTO);
        log.info("基于用户余额支付成功 {}", payOrderFormDTO);
        return Result.success();
    }

    @ApiOperation("取消支付订单")
    @PutMapping("/cancel/{id}")
    @CacheRemoveByUserId(keys = Constants.REDIS_KEY_PAY_ORDERS)
    public Result<String> cancelPayOrder(@ApiParam("支付订单id") @PathVariable("id") Long id) {
        log.info("取消支付订单 id: {}", id);
        payOrderService.cancelPayOrder(id);
        log.info("取消支付订单成功 id: {}", id);
        return Result.success();
    }
}
